package com.gouda.core.service.impl.serviceIntroduce;

import com.gouda.core.dao.ServiceTypeDao;
import com.gouda.core.dao.UserDao;
import com.gouda.core.dao.UserServiceIntroduceDao;
import com.gouda.core.entity.ServiceTypeEntity;
import com.gouda.core.entity.UserEntity;
import com.gouda.core.entity.UserServiceIntroduceEntity;
import com.gouda.core.enums.GeneralStateEnum;
import com.gouda.core.service.serviceIntroduce.UserServiceIntroduceService;
import org.amethyst.atlas.basic.manufactory.specifics.DBEntityFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by souu on 15/12/6.
 */
@Service
public class UserServiceIntroduceServiceImpl implements UserServiceIntroduceService {

    @Autowired
    private ServiceTypeDao serviceTypeDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserServiceIntroduceDao userServiceIntroduceDao;

    @Override
    public void createOrUpdateUserServiceIntroduce(long serviceTypeId, long uid, int num, GeneralStateEnum stateEnum) {
        if (serviceTypeId <= 0 || uid <= 0) {
            return;
        }
        ServiceTypeEntity serviceType = this.serviceTypeDao.unique(ServiceTypeEntity.class, serviceTypeId);
        if (serviceType == null) {
            return;
        }
        UserEntity user = this.userDao.unique(UserEntity.class, uid);
        if (user == null) {
            return;
        }

        UserServiceIntroduceEntity entity = this.userServiceIntroduceDao.getUserServiceIntroduce(serviceTypeId, uid);
        if (entity == null) {
            entity = DBEntityFactory.getFactory().generateDBEntity(UserServiceIntroduceEntity.class);
            entity.setCreateTime(new Date());
            entity.setServiceName(serviceType.getServiceName());
            entity.setServiceNum(num);
            entity.setState(stateEnum.getCode());
            entity.setStId(serviceTypeId);
            entity.setUid(uid);
            this.userServiceIntroduceDao.insert(entity);
        } else {
            entity.setServiceName(serviceType.getServiceName());
            entity.setServiceNum(entity.getServiceNum() + num);
            entity.setState(stateEnum.getCode());
            entity.setStId(serviceTypeId);
            entity.setUid(uid);
            this.userServiceIntroduceDao.update(entity);
        }

    }

    @Override
    public boolean isDisplay(long serviceTypeId, long uid) {
        if (serviceTypeId <= 0 || uid <= 0) {
            return true;
        }
        UserServiceIntroduceEntity entity = this.userServiceIntroduceDao.getUserServiceIntroduce(serviceTypeId, uid);
        if (entity == null) {
            return true;
        }

        if (entity.getServiceNum() < 3 && GeneralStateEnum.fromInteger(entity.getState()) == GeneralStateEnum.NO) {
            return true;
        }
        return false;
    }
}
